package com.teemor.tim.processor.state;

import com.teemor.tim.command.model.customer.DisConnectCommandd;
import com.teemor.tim.enums.UserStateEnum;
import com.teemor.tim.model.user.UserStateModel;
import com.teemor.tim.command.CommandExecute;
import com.teemor.tim.enums.UserType;
import com.teemor.tim.processor.UserStateProcessor;
import com.teemor.tim.cache.UserStateCache;
import com.teemor.tim.utils.ContextWarer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/12/14 10:07
 */
@Component
public class DefaultUserStateProcessor implements UserStateProcessor {

    @Resource
    private UserStateCache userStateCache;

    public static volatile DefaultUserStateProcessor instance;
    public static DefaultUserStateProcessor getInstance() {
        if (instance == null) {
            synchronized (DefaultUserStateProcessor.class) {
                if (instance == null) {
                    instance = ContextWarer.getBean(DefaultUserStateProcessor.class);
                }
            }
        }
        return instance;
    }

    @Override
    public void onConnect(UserState userState) {
        UserStateModel exist = Optional.ofNullable(userStateCache.getState(userState.getUserId())).orElse(new UserStateModel(userState));
        exist.setState(userState.getState());
        userStateCache.cacheState(exist);
    }

    @Override
    public void onDisconnect(UserState userState) {
        UserStateModel exist = userStateCache.removeState(userState.getUserId());
        if (Objects.nonNull(exist)) {
            this.wrapperDisconnectCommand(exist);
        }
    }

    @Override
    public  List<UserStateModel> getUserStates(UserType userType) {
        return getInstance().userStateCache.getStates(userType);
    }

    private void wrapperDisconnectCommand(UserStateModel userStateModel) {
        if (userStateModel == null) return;
        DisConnectCommandd command;
        if (UserType.CUSTOMER_SERVICE.toString().equals(userStateModel.getUserType())) {
            command = new DisConnectCommandd("CS.CsDisconnect");
        } else {
            command = new DisConnectCommandd("CS.UserDisconnect");
        }
        command.setUserId(userStateModel.getUserId());
        command.setUserType(userStateModel.getUserType());
        command.setUserStateModels(userStateModel.getSessionUsers());
        CommandExecute.instance().execute(command);
    }


    //处理用户状态变化
    public static void processUserState(UserStateModel userModel) {
        UserStateEnum userState = UserStateEnum.valueOf(userModel.getState());
        switch (userState) {
            case Login:
                getInstance().onConnect(userModel);
                break;
            case Logout:
            case Disconnect:
                getInstance().onDisconnect(userModel);
                break;
        }
    }

}
